import Vue from 'vue'
import  VueRouter from 'vue-router'
import login from '@/view/login/login'
import Layout from '@/view/layout/index'
import Article from '@/view/article/index'
import Image from '@/view/image/index'
import Publish from '@/view/publish/index'
import Comment from '@/view/comment/index'
import Fans from '@/view/fans/index'
import Settings from '@/view/settings/index'

Vue.use(VueRouter)
const routes =  [{
  path: '/login',
  name: 'login',
  component: login
},
{
  path: '/',
  // 命名路由 layout 有一个默认子路由，这个名字没有意义
  // 正确的做法：如果有默认子路由，就不要给父路由起名字
  component: Layout,
  children: [{
      path: '', //默认子路由
      name: 'home',
      component: Article
    },
    {
      path: '/article',
      name: 'article',
      component: Article
    },
    {
      path: '/image',
      name: 'image',
      component: Image
    },
    {
      path: '/publish',
      name: 'publish',
      component: Publish
    },
    {
      path: '/comment',
      name: 'comment',
      component: Comment
    },
    {
      path: '/fans',
      name: 'fans',
      component: Fans
    },
    {
      path: '/settings',
      name: 'settings',
      component: Settings
    }
  ]
},
// {
//   path: '/',
//   name: 'home',
//   component: Home
// }
]

const router = new VueRouter({
  routes
})
// to:要去的路由信息
// from:来自哪里的路由信息
// next:放行方法
router.beforeEach((to, from, next) => {
  // 如果要访问的页面不是/login 校验登录状态
  // 如果没有登录，则跳转到登录页面
  // 如果登录了，则允许通过
  // 允许通过
  // next()
  const user = JSON.parse(localStorage.getItem('user'));
  if (to.path !== '/login') {
    if (user) {
      // 登录了
      next()
    } else {
      // 没有登录
      next('/login')
    }
  } else {
    // 登录页面 ， 正常允许通过
    next();
  }
})

export default router;
